// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,
     
    properties: {
        ServerModule: cc.Node,
        roomId_input_editbox: cc.EditBox,
        avatarSprite: cc.Sprite,
        usernameLable: cc.Label,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.initServerModule()

        let _this = this

        qg.gameLogin({
            forceLogin: 1, //强制登录，未登录时会弹出登录对话框
            appid: "104140205", //appid需要与华为开发者联盟后台配置一致
            success: function (res) {
                console.log("game login: success-llp", res);
                let playerId= res.playerId
                let displayName = res.displayName
                let imageUri = res.imageUri
                console.log("#########imageUri is:"+imageUri)
                console.log("game login res:", playerId,displayName,imageUri);
                _this.applyUserInfoNode(_this, displayName, imageUri)
            },
            fail(data, code) {
                console.log("on gameLogin fail: " + data + "," + code);
            },
            complete() {
                console.log("on gameLogin: complete");
            }
        });
    },

    applyUserInfoNode(_this, username, avatarUrl){
        console.log("call applyUserInfoNode")
        // cc.assetManager.loadRemote("http://c-ssl.duitang.com/uploads/item/201807/14/20180714183007_bvlpc.jpg", function (err, texture) {
            cc.assetManager.loadRemote(avatarUrl, function (err, texture) {
            console.log("cc.assetManager.loadRemote")
            var spf = new cc.SpriteFrame();
            spf.initWithTexture(texture);
            _this.avatarSprite.spriteFrame = spf;
        });

        _this.usernameLable.string = username
        // _this.usernameLable.string = "1234567"
    },

    initServerModule() {
        // 初始化连接
        let url = cfg.SERVER_HOST + ":" + cfg.SERVER_PORT
       
        this.ServerModule.getComponent('ServerModule').initServerModule(url)
    },

    onJoinRoom () {
        console.log("onJoinRoom called")
        let roomId = this.roomId_input_editbox.string
        if ("" == roomId || "" == roomId.trim()) {
            this.roomId_input_editbox.string = ""
            return
        }
        console.log("onJoinRoom, roomId:" + roomId)
        let userInfo = {
            "username": "阿西吧",
            "userid": "123"
        }
        this.ServerModule.getComponent('ServerModule').sendJoinRoomEvent(roomId, userInfo)
        cc.director.loadScene("draw");
    },

    // update (dt) {},
});
